<template>
  <div>
    <!-- 标题 -->
    <!-- <h4>用户管理</h4> -->
    <!-- 菜单 -->
    <el-form :inline="true" :model="form" class="demo-form-inline" label-width="auto" size="mini">
      <el-form-item label="用户名：">
        <el-input class="btn-input" v-model="userInfo.userName" clearable></el-input>
      </el-form-item>
      <el-form-item label="姓名：">
        <el-input class="btn-input" v-model="userInfo.name" clearable></el-input>
      </el-form-item>
      <el-form-item label="状态：">
        <el-select v-model="userInfo.state" clearable placeholder="请选择" class="btn-input">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" class="btn-set" icon="el-icon-search" @click="search">
          查询
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="success" icon="el-icon-plus" class="btn-set" @click="add">新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="danger" icon="el-icon-delete" class="btn-set" @click="delList">
          删除
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-upload
          class="upload-demo"
          ref="upload"
          action="http://localhost:8080/user/import"
          :on-success="importSuccess"
          :show-file-list="false"
        >
          <el-button type="primary">
            <i class="el-icon-upload el-icon--right"></i>
            Excel导入
          </el-button>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="btn-set" @click="handleDownload">
          <i class="el-icon-download el-icon--right"></i>
          Excel导出
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 用户列表 -->
    <el-table
      :data="userList"
      border
      style="width: 100%"
      size="mini"
      :max-height="min_height"
      :cell-style="{ 'text-align': 'center' }"
      :header-cell-style="{ 'text-align': 'center' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="40"></el-table-column>
      <el-table-column fixed prop="userId" label="序号" width="50" resizable></el-table-column>
      <el-table-column prop="userName" label="用户名" width="auto"></el-table-column>
      <el-table-column prop="name" label="姓名" width="80"></el-table-column>
      <el-table-column prop="gender" label="性别" width="50"></el-table-column>
      <el-table-column prop="telephone" label="联系电话" width="auto"></el-table-column>
      <el-table-column prop="email" label="邮箱" width="auto"></el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="auto">
        <template slot-scope="{ row }">
          {{ row.createTime ? row.createTime.split('T')[0] : '' }}
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="最后修改时间" width="auto">
        <template slot-scope="{ row }">
          {{ row.updateTime ? row.updateTime.split('T')[0] : '' }}
        </template>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="70">
        <template slot-scope="scope">
          <!-- scope.row 可以取到当前一行的数据 -->
          <el-switch v-model="scope.row.state" active-value="1" inactive-value="0"></el-switch>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="175">
        <template slot-scope="scope">
          <!-- 修改按钮 -->
          <el-tooltip effect="dark" content="编辑用户" placement="top" :enterable="false">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              :disabled="scope.row.userId === 1"
              @click="edit(scope.row)"
            ></el-button>
          </el-tooltip>
          <!-- 删除按钮 -->
          <el-tooltip effect="dark" content="删除用户" placement="top" :enterable="false">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              :disabled="scope.row.userId === 1"
              @click="del(scope.row)"
            ></el-button>
          </el-tooltip>
          <!-- 分配角色按钮 -->
          <el-tooltip effect="dark" content="设置角色" placement="top" :enterable="false">
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              :disabled="scope.row.userId === 1"
              @click="editUser(scope.row)"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="userInfo.pageNo"
        :page-sizes="[10, 15, 20]"
        :page-size="userInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="count"
      ></el-pagination>
    </div>
    <!-- 新增 编辑弹窗 -->
    <el-dialog
      :title="this.form.userId ? '编辑用户' : '新增用户'"
      :visible.sync="dialogFormVisible"
      width="40%"
      @close="close"
    >
      <el-form :model="form" :rules="rules" class="demo-form-inline" ref="ruleForm">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="用户名:" :label-width="formLabelWidth" prop="userName">
              <el-input
                v-model="form.userName"
                autocomplete="on1"
                class="dialog_ipt"
                placeholder="请输入用户名"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="姓名:" :label-width="formLabelWidth" prop="name">
              <el-input
                v-model="form.name"
                autocomplete="off"
                class="dialog_ipt"
                placeholder="请输入姓名"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              v-if="!form.userId"
              label="密码:"
              :label-width="formLabelWidth"
              prop="password"
            >
              <el-input
                type="password"
                v-model="form.password"
                autocomplete="off"
                class="dialog_ipt"
                placeholder="请输入密码"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              v-if="!form.userId"
              label="确认密码:"
              :label-width="formLabelWidth"
              prop="checkPass"
            >
              <el-input
                type="password"
                v-model="form.checkPass"
                autocomplete="off"
                class="dialog_ipt"
                placeholder="请确认密码"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="性别" :label-width="formLabelWidth" prop="gender">
              <el-select v-model="form.gender" placeholder="请选择性别" autocomplete="off">
                <el-option label="男" value="男"></el-option>
                <el-option label="女" value="女"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="联系电话:" :label-width="formLabelWidth" prop="telephone">
              <el-input
                v-model="form.telephone"
                autocomplete="off"
                class="dialog_ipt"
                placeholder="请输入联系电话"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="邮箱:" :label-width="formLabelWidth" prop="email">
              <el-input
                v-model="form.email"
                autocomplete="off"
                class="dialog_ipt"
                placeholder="请输入邮箱"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="状态:" :label-width="formLabelWidth">
              <template>
                <el-radio v-model="form.state" label="1">有效</el-radio>
                <el-radio v-model="form.state" label="0">无效</el-radio>
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注:" :label-width="formLabelWidth">
              <el-input
                v-model="form.remake"
                type="textarea"
                autocomplete="off"
                class="dialog_ipt"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="btnOk">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 设置角色弹窗 -->
    <el-dialog title="角色设置" :visible.sync="dialogTableVisible" @close="closeRole">
      <el-form :model="form">
        <el-form-item label="用户名:" :label-width="formLabelWidth" prop="userName">
          <el-input
            v-model="form.userName"
            autocomplete="on1"
            class="dialog_ipt"
            :disabled="true"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-table
        :data="roleList"
        border
        style="width: 100%"
        size="mini"
        max-height="250px"
        @selection-change="RoleSelectionChange"
      >
        <el-table-column type="selection" width="auto"></el-table-column>
        <el-table-column fixed prop="roleId" label="序号" width="50" resizable></el-table-column>
        <el-table-column prop="roleSet" label="用户编码" width="auto"></el-table-column>
        <el-table-column prop="roleName" label="角色名称" width="80"></el-table-column>
        <el-table-column prop="effectTime" label="生效日期" width="auto"></el-table-column>
        <el-table-column prop="uneffectTime" label="失效日期" width="auto"></el-table-column>
        <el-table-column prop="status" label="状态" width="70">
          <template slot-scope="scope">
            <!-- scope.row 可以取到当前一行的数据 -->
            <!-- {{ scope.row }} -->
            <el-switch v-model="scope.row.status" active-value="1" inactive-value="0"></el-switch>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeRole">取 消</el-button>
        <el-button type="primary" @click="RoleOk">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { MessageBox, Message } from 'element-ui'
import {
  selectUserAPI,
  insertAPI,
  selectidAPI,
  deletUserAPI,
  updateUserAPI,
  grantPowerAPI,
  getOneAPI
} from '../../api/userAPI'
import { selectroleAPI } from '../../api/roleAPI'

export default {
  name: 'MyUser',
  data() {
    // 重新输入密码的验证
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.form.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      // 用户列表数据
      userList: [],
      count: 1,
      // 查询数据
      userInfo: {
        userName: '',
        name: '',
        state: '',
        // 页码数
        pageNo: 1,
        // 展示的数据条数
        pageSize: 10
      },
      // 表格最大高度
      min_height: 470,
      // 选项数据
      options: [
        {
          value: null,
          label: '全部'
        },
        {
          value: 1,
          label: '有效'
        },
        {
          value: 0,
          label: '无效'
        }
      ],
      // 新增 编辑弹窗开关
      dialogFormVisible: false,
      // 设置角色弹窗
      dialogTableVisible: false,
      // 弹窗数据
      form: {
        userName: '',
        name: '',
        gender: '',
        password: '',
        checkPass: '',
        telephone: '',
        email: '',
        // 状态
        state: '1',
        remake: ''
      },
      // 编辑用户的数据
      editForm: {},
      // 表格选中的数据
      multipleSelection: [],
      formLabelWidth: '120px',
      // 弹出表单规则
      rules: {
        userName: [
          { required: true, message: '请输入您的用户名', trigger: 'blur' },
          {
            pattern: /^[A-Za-z\u4E00-\u9FA5]{6,20}$/,
            message: '请输入由字母汉字组成且长度6~20位的用户名',
            trigger: 'blur'
          }
        ],
        name: [
          { required: true, message: '请输入您的姓名', trigger: 'blur' },
          {
            pattern: /^[A-Za-z\u4E00-\u9FA5]{2,50}$/,
            message: '请输入由字母汉字组成且长度2-50位的姓名',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        checkPass: [{ validator: validatePass2, trigger: 'blur' }],
        gender: [{ message: '请输入您的性别', trigger: 'blur' }],
        telephone: [
          {
            pattern: /^1(3\d|47|5((?!4)\d)|7(0|1|[6-8])|8\d)\d{8,8}$/,
            message: '请输入正确格式的手机号',
            trigger: 'blur'
          }
        ],
        email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }]
      },
      setRole: {
        userId: '',
        roleIds: []
      },
      // 角色信息
      roleList: [],
      roleInfo: {
        pageNo: 1,
        pageSize: 10
      },
      // 勾选的角色信息
      RoleSelectionList: []
    }
  },
  created() {
    this.getselectuser()
  },

  methods: {
    // 分页查询数据
    async getselectuser() {
      const result = await selectUserAPI(this.userInfo)
      this.userList = result.conditionlist
      this.count = result.count
    },
    // 分页数据条数
    handleSizeChange(val) {
      this.userInfo.pageSize = val
      this.getselectuser(this.userInfo)
    },
    // 分页页码
    handleCurrentChange(val) {
      this.userInfo.pageNo = val
      this.getselectuser(this.userInfo)
    },
    // 点击搜索事件
    async search() {
      const data = await selectUserAPI(this.userInfo)
      this.userList = data.conditionlist
    },
    // 批量删除
    async delList() {
      const arr = []
      this.multipleSelection.forEach(item => {
        arr.push(item.userId)
      })
      try {
        await MessageBox.confirm('您确定要删除吗')
        const data = await deletUserAPI(arr)
        if (data.code === '1') {
          Message.success('删除成功')
          this.getselectuser()
        } else {
          Message.error('您没有此权限')
        }
      } catch (err) {
        Message('取消删除')
      }
    },
    // 点击新增事件
    add() {
      this.dialogFormVisible = true
      this.editForm = {}
    },
    // 点击编辑事件
    async edit(row) {
      const data = await selectidAPI({ userId: row.userId })
      this.editForm = data
      this.form = JSON.parse(JSON.stringify(row))
      this.dialogFormVisible = true
    },
    // 点击删除事件
    async del(row) {
      try {
        await MessageBox.confirm('您确定要删除吗')
        const data = await deletUserAPI([row.userId])
        if (data.code === '1') {
          Message.success('删除成功')
          this.getselectuser()
        } else {
          Message.error('您没有此权限')
        }
      } catch (err) {
        Message('取消删除')
      }
    },
    // 点击设置角色事件
    async editUser(row) {
      this.dialogTableVisible = true
      this.form = JSON.parse(JSON.stringify(row))
      const result = await selectroleAPI(this.roleInfo)
      this.roleList = result.conditionlist
      this.setRole.userId = row.userId
    },
    // 弹窗关闭事件
    close() {
      this.form = {}
      this.dialogFormVisible = false
      this.$refs.ruleForm.resetFields()
    },
    closeRole() {
      this.form.username = ''
      this.dialogTableVisible = false
    },
    // 设置角色确认事件
    async RoleOk() {
      const arr = []
      this.RoleSelectionList.forEach(item => {
        arr.push(item.roleId)
      })
      this.setRole.roleIds = arr
      const result = await grantPowerAPI(this.setRole.userId, this.setRole.roleIds)
      if (result.code === '1') {
        Message.success('设置角色成功')
        this.closeRole()
      } else {
        Message.error('您没有此权限')
        this.closeRole()
      }
      // this.dialogTableVisible = false
    },
    //  新增 编辑 弹窗按钮确认事件
    btnOk() {
      this.$refs.ruleForm.validate(async val => {
        // 如果有id那就是编辑事件
        if (this.editForm.userId) {
          try {
            if (val) {
              const result = await updateUserAPI(this.form)
              if (result.code === '1') {
                Message.success('修改成功')
                this.close()
                this.getselectuser()
              } else {
                Message.error('您没有此权限')
                this.close()
              }
            }
          } catch (err) {
            this.close()
          }
        }
        // 如果没id则就是新增事件
        else {
          if (val) {
            const result = await getOneAPI({ userName: this.form.userName })
            if (result.userName) {
              Message.error('该用户名已存在')
              this.close()
            } else {
              try {
                await MessageBox.confirm('您确定要新增吗')
                const data = await insertAPI(this.form)
                if (data.code === '1') {
                  this.close()
                  Message.success('新增成功')
                  this.getselectuser()
                } else {
                  Message.error('您没有此权限')
                }
              } catch (err) {
                Message.error('新增失败')
              }
            }
          }
        }
      })
    },

    // 获取勾选的用户信息存到 multipleSelection中
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 获取勾选的角色信息存到
    RoleSelectionChange(val) {
      this.RoleSelectionList = val
    },
    // 批量导入事件
    importSuccess(res) {
      if (res) {
        this.getselectuser()
      }
    },
    // 批量导出事件
    handleDownload() {
      import('@/vendor/Export2Excel').then(excel => {
        // excel表示导入的模块对象
        const tHeader = {
          id: 'userId',
          用户名: 'userName',
          姓名: 'name',
          性别: 'gender',
          电话: 'number',
          邮箱: 'email',
          修改时间: 'createTime',
          最后修改时间: 'updateTime',
          状态: 'state'
        }
        const data = this.formatJson(tHeader, this.multipleSelection)
        excel.export_json_to_excel({
          header: Object.keys(tHeader), // 表头 必填
          data, // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    formatJson(headers, rows) {
      return rows.map(item => {
        return Object.keys(headers).map(key => {
          return item[headers[key]]
        }) // ["132", '张三’， ‘’，‘’，‘’d]
      }) // return rows.map(item => Object.keys(headers).map(key => item[headers[key]])) // 需要处理时间格式问题
    }
  }
}
</script>

<style lang="less" scoped>
.btn-set {
  margin: 0 5px;
}
.btn-input {
  width: 140px;
}
::v-deep .el-dialog {
  padding: 0 30px;
}
.dialog_ipt {
  width: 260px;
}
.el-pagination {
  margin-top: 5px;
  position: absolute;
  left: 50%;
  transform: translate(-50%, 0);
}
</style>
